package com.aiti.myproject.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aiti.myproject.shared.Tag;
import com.aiti.myproject.shared.UploadImage;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class TagDAO {
	private DatastoreService datastore;
	private static final String CREATE_AT = "createAt";
	private static final String TAG_ID = "tagId";
	private static final String PHOTO_KEY = "photoKey";
	private static final String BODY = "body";
	private static final String X = "x";
	private static final String Y = "y";

	public TagDAO() {
		datastore = DatastoreServiceFactory.getDatastoreService();
	}

	/**
	 * @param tag
	 *            The Tag object we want persisted
	 * @return a String encoded Key for the saved object
	 */
	public String put(Tag tag) {
		Entity tagEntity = new Entity(Tag.class.getSimpleName());

		tagEntity.setProperty(CREATE_AT, tag.getCreateAt());
		tagEntity.setProperty(TAG_ID, tag.getTagId());
		tagEntity.setProperty(PHOTO_KEY, tag.getPhotoKey());

		tagEntity.setUnindexedProperty(BODY, tag.getBody());
		tagEntity.setUnindexedProperty(X, tag.getX());
		tagEntity.setUnindexedProperty(Y, tag.getY());

		Key key = datastore.put(tagEntity);
		String encodedKey = KeyFactory.keyToString(key);
		return encodedKey;
	}

	@SuppressWarnings("deprecation")
	public List<Tag> getForImage(UploadImage image) {
		Query query = new Query(Tag.class.getSimpleName());
		query.addFilter(PHOTO_KEY, FilterOperator.EQUAL, image.getKey());

		List<Tag> results = new ArrayList<Tag>();

		for (Entity entity : datastore.prepare(query).asIterable(
				FetchOptions.Builder.withDefaults())) {
			Tag tag = new Tag();
			tag.setPhotoKey((String) entity.getProperty(PHOTO_KEY));
			tag.setBody((String) entity.getProperty(BODY));
			tag.setCreateAt((Date) entity.getProperty(CREATE_AT));
			tag.setTagId((String) entity.getProperty(TAG_ID));
			tag.setX((Long) entity.getProperty(X));
			tag.setY((Long) entity.getProperty(Y));
			results.add(tag);
		}

		return results;
	}
}
